import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/register')
  },
  {
    path: '/layout',
    name: 'Layout',
    component: () => import('@/views/layout'),
    meta: {
      hasLogin: true
    },
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/home')
      },
      {
        path: '/user-info',
        name: 'Userinfo',
        component: () => import('@/views/user/userInfo.vue')
      },
      {
        path: '/user-avatar',
        name: 'UserAvatar',
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: '/user-pwd',
        name: 'UserPwd',
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: '/art-cate',
        name: 'ArtCate',
        component: () => import('@/views/article/artCate.vue')
      },
      {
        path: '/art-list',
        name: 'ArtList',
        component: () => import('@/views/article/artList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 白名单
const whiteList = ['/login', '/register']

// 前置路由 用户登录异步调用方法获取用户信息
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (!store.state.userInfo) {
      store.dispatch('getUserInfoActions')
      // dispatch：含有异步操作，数据提交至 actions ，可用于向后台提交数据
      // commit：同步操作，数据提交至 mutations ，可用于读取用户信息写到缓存里
    }
    next()
  } else {
    // 无token仅可访问白名单地址
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
